#!/usr/bin/env perl

# Sesame 2.x SPARQL SELECT query, with result as TSV.
#
# Copyright 2013 by David Booth
# Code home: http://code.google.com/p/rdf-pipeline/
# See license information at http://code.google.com/p/rdf-pipeline/ 
#
# Usage: $0 filename.rq

################### Generic preparation ####################
use warnings;
use strict;
my $debug = 0;
$ENV{SPARQL_SERVER} or die "$0: ERROR: SPARQL_SERVER env var is not set.  Example:
  export SPARQL_SERVER=http://localhost:8080/openrdf-workbench/repositories/rdf-pipeline-test\n";
@ARGV <= 1 or die "Usage: $0 [ filename.rq ]\n";
@ARGV = ( "-" ) if !@ARGV;	# Default to stdin

my $f = $ARGV[0];
my $tmpDir = $ENV{TMPDIR} || "/tmp";
$tmpDir =~ s|([^\/])\/$|$1|;    # Strip trailing slash
my $tmpSparql = "";
if ($f eq "-") {
	my $s = join("", <>);
	$tmpSparql = "$tmpDir/sparql-select-$$.rq";
	&WriteFile($tmpSparql, $s);
	$f = $tmpSparql;
	}
-e $f or die "$0: ERROR: File not found: $f\n";
-f $f or die "$0: ERROR: Not a plain file: $f\n";

my $qf = quotemeta($f);

################### Server-type-specific code ####################
my $dir = $0;
$dir =~ s/\/[^\/]+$//;
my $qdir = quotemeta($dir);
my $qss = quotemeta($ENV{SPARQL_SERVER});
my $cmd = "/usr/bin/curl -s  --data-urlencode  query\@$qf $qss/query?queryLn=SPARQL | perl -p -e 's/\\\\r//g' | xsltproc $qdir/sparql-results-tsv.xsl - | iconv -f UTF-16 -t UTF-8";
warn "cmd: $cmd\n" if $debug;
!system($cmd) or die "$0: $?\n";

####################### Generic cleanup #########################
unlink($tmpSparql) if $tmpSparql && !$debug;
exit 0;

############ WriteFile ##########
# Perl function to write a string to a file.
sub WriteFile
{
@_ == 2 || die;
my ($f, $s) = @_;
open(my $fh, ">$f") || die;
print $fh $s;
close($fh) || die;
}

